package mastermind.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.util.Locale;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.SpringLayout;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;

import mastermind.gui.actions.AboutAction;
import mastermind.gui.actions.BlueAction;
import mastermind.gui.actions.GreenAction;
import mastermind.gui.actions.LoginAction;
import mastermind.gui.actions.MagentaAction;
import mastermind.gui.actions.OrangeAction;
import mastermind.gui.actions.QuitAction;
import mastermind.gui.actions.RedAction;
import mastermind.gui.actions.RegisterAction;
import mastermind.gui.actions.SettingsAction;
import mastermind.gui.actions.StartGameAction;
import mastermind.gui.actions.SubmitAction;
import mastermind.gui.actions.YellowAction;
import mastermind.socket.protocol;
import mastermind.socket.socketConnect;

public class Frame extends JFrame {
	
	private Action quitAction;
	private Action submitAction;
	private Action registerAction;
	private Action loginAction;
	private Action startGameAction;
	private Action settingsAction;
	private Action aboutAction;
	
	private Action redAction;
	private Action blueAction;
	private Action greenAction;
	private Action orangeAction;
	private Action magentaAction;
	private Action yellowAction;
	
	private	JTable table;
	private JTable pegTable;
	private JPanel topPanel;
	private JPanel tabelPanel;
	private JPanel btnPanel;
	private JPanel colourPanel;
	
	private JButton btnQuit;
	private JButton btnSubmit;
	private JButton btnRegister;
	private JButton btnLogin;
	private JButton btnStartGame;
	
	private JButton btnRed;
	private JButton btnYellow;
	private JButton btnGreen;
	private JButton btnBlue;
	private JButton btnMagenta;
	private JButton btnOrange;
	
	private JButton btnSettings;
	private JButton btnAbout;
	
	private JTextField txtScores;
	
	private CustomCellRenderer crr;
	private CustomCellRendererPegs crrpegs;
	
	private String serverAddress;
	private String serverPort;
	
	private socketConnect clientSocket;
	
	private boolean loggedIn = false;
	
	private int turnCount;
	private boolean gameStarted = false;
	private String userName;
	
	String columnNames[] = {"Column 1", "Column 2", "Column 3", "Column 4"};

	String dataValues[][] =
	{
		{" ", " ", " ", " "},
		{" ", " ", " ", " "},
		{" ", " ", " ", " "},
		{" ", " ", " ", " "},
		{" ", " ", " ", " "},
		{" ", " ", " ", " "},
		{" ", " ", " ", " "},
		{" ", " ", " ", " "},
		{" ", " ", " ", " "},
		{" ", " ", " ", " "},
	};
	
	String dataValuesPegs[][] =
	{
		{"  X", "  X", "  X", "  X"},
		{"  X", "  X", "  X", "  X"},
		{"  X", "  X", "  X", "  X"},
		{"  X", "  X", "  X", "  X"},
		{"  X", "  X", "  X", "  X"},
		{"  X", "  X", "  X", "  X"},
		{"  X", "  X", "  X", "  X"},
		{"  X", "  X", "  X", "  X"},
		{"  X", "  X", "  X", "  X"},
		{"  X", "  X", "  X", "  X"},
	};
	
    private class FrameWindowListener extends WindowAdapter {
    	
        /** Invokes quit action when user attempts to close window */
        @Override
        public void windowClosing(WindowEvent we) 
        {
        	try 
        	{
				clientSocket.getOutputStream().writeInt(protocol.CLIENT_CLOSING);
			} 
        	catch (IOException e) 
        	{
				e.printStackTrace();
			}
        	clientSocket.closeSocket();
            quitAction.actionPerformed(null);
        }
    }
    
	/**
	 * returns main table
	 */
    public JTable getBoardTable()
    {
    	return table;
    }
    
	/**
	 * returns peg table
	 */
    public JTable getPegTable()
    {
    	return pegTable;
    }
    
	/**
	 * returns saved server address
	 */
    public String getServerAddress()
    {
    	return serverAddress;
    }
    
	/**
	 * returns saved server port
	 */
    public String getServerPort()
    {
    	return serverPort;
    }
    
	/**
	 * set server address
	 */
    public void setServerAddress(String s)
    {
    	serverAddress = s;
    }
    
	/**
	 * set server port
	 */
    public void setServerPort(String s)
    {
    	serverPort = s;
    }
    
	/**
	 * create new socket to server
	 */
    public socketConnect connect()
    {
    	if(clientSocket == null)
    	{
    		clientSocket = new socketConnect(this);
    	}
    	return clientSocket;
    }
    
	/**
	 * close sockets
	 */
    public void closeSocket()
    {
    	clientSocket.closeSocket();
    }
    
	/**
	 * if login was successful
	 */
    public void setLoginSuccess()
    {
    	loggedIn = true;
    }
    
	/**
	 * retrieve login status
	 */
    public boolean getLoginStatus()
    {
    	return loggedIn;
    }
    
    public JButton getStartGameButton()
    {
    	return btnStartGame;
    }
    
	/**
	 * set turn count
	 */
    public void setTurnCount(int t)
    {
    	turnCount = t;
    }
    
	/**
	 * retrieve turn count
	 */
    public int getTurnCount()
    {
    	return turnCount;
    }
    
    public void setGameStarted(boolean b)
    {
    	gameStarted = b;
    }
    
    public boolean getGameStarted()
    {
    	return gameStarted;
    }
    
	/**
	 * set username that logged in
	 */
    public void setUserName(String u)
    {
    	userName = u;
    	txtScores.setText(userName + " your average is %s. Average for all players is %s");
    }
    public Frame() {
    	
    	serverAddress = "127.0.0.1"; //default server values
    	serverPort = "2011";
    	
    	topPanel = new JPanel();
    	    	
    	redAction = new RedAction(this);
    	yellowAction = new YellowAction(this);
    	greenAction = new GreenAction(this);
    	blueAction = new BlueAction(this); //create button actions
    	orangeAction = new OrangeAction(this);
    	magentaAction = new MagentaAction(this);
    	
    	registerAction = new RegisterAction(this);
    	loginAction = new LoginAction(this);
    	quitAction = new QuitAction(this);
    	startGameAction = new StartGameAction(this);
    	settingsAction = new SettingsAction(this); // register button actions
    	aboutAction = new AboutAction();
    	submitAction = new SubmitAction(this);
    	    	
    	topPanel.setPreferredSize(new Dimension(400,700));
    	topPanel.setLayout(new FlowLayout());
    	getContentPane().add(topPanel); //create panels and add them to frame
    	    	
    	btnPanel = new JPanel();
    	btnPanel.setLayout(new GridLayout(3,2));
    	btnPanel.setBorder(BorderFactory.createLoweredBevelBorder());
    	
    	colourPanel = new JPanel();
    	colourPanel.setLayout(new FlowLayout());
    	colourPanel.setBorder(BorderFactory.createLoweredBevelBorder());
    	
    	btnSubmit = new JButton(submitAction);
    	btnSubmit.setText("Submit");
    	btnAbout = new JButton(aboutAction);
    	btnAbout.setText("About");
    	btnSettings = new JButton(settingsAction);
    	btnSettings.setText("Settings");
    	
    	btnRed = new JButton(redAction);
    	btnRed.setPreferredSize(new Dimension(40,30));
    	btnYellow = new JButton(yellowAction);
    	btnYellow.setPreferredSize(new Dimension(40,30));
    	btnGreen = new JButton(greenAction);
    	btnGreen.setPreferredSize(new Dimension(40,30));
    	btnBlue = new JButton(blueAction);
    	btnBlue.setPreferredSize(new Dimension(40,30));
    	btnMagenta = new JButton(magentaAction);
    	btnMagenta.setPreferredSize(new Dimension(40,30));
    	btnOrange = new JButton(orangeAction);
    	btnOrange.setPreferredSize(new Dimension(40,30)); //set actions to buttons
    	
    	btnRegister = new JButton(registerAction);
    	btnRegister.setText("Register");
    	
    	btnLogin = new JButton(loginAction);
    	btnLogin.setText("Login");
    	
    	btnQuit = new JButton(quitAction);
    	btnQuit.setText("Quit");
    	
    	btnStartGame = new JButton(startGameAction);
    	btnStartGame.setText("Start Game");
    	
    	btnRed.setBackground(Color.red);
    	btnYellow.setBackground(Color.yellow);
    	btnGreen.setBackground(Color.green); //colour buttons
    	btnBlue.setBackground(Color.blue);
    	btnMagenta.setBackground(Color.magenta);
    	btnOrange.setBackground(Color.orange);
    	
    	txtScores = new JTextField(userName + " your average is %s. Average for all players is %s");
    	txtScores.setPreferredSize(new Dimension(600,20));
    	txtScores.setEditable(false);
  
    	//table = new JTable(dataValues, columnNames);
    	table = new JTable(dataValues, columnNames) {
    	    public boolean isCellEditable(int rowIndex, int vColIndex) {
    	        return false;
    	    }
    	};
		table.setShowHorizontalLines(true);
		table.setCellSelectionEnabled(true); //set table properties
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table.getTableHeader().setResizingAllowed(false);
		
    	//pegTable = new JTable(dataValuesPegs, columnNames);
		pegTable = new JTable(dataValuesPegs, columnNames) {
    	    public boolean isCellEditable(int rowIndex, int vColIndex) {
    	        return false;
    	    }
    	};
    	pegTable.setShowHorizontalLines(true);
    	pegTable.setCellSelectionEnabled(true); //set table properties
    	pegTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    	pegTable.getTableHeader().setResizingAllowed(false);
		pegTable.setRowHeight(50);
		
		
		for(int i = 0; i < pegTable.getColumnCount(); i++) //set column width
		{
			pegTable.getColumnModel().getColumn(i).setPreferredWidth(20);
		}
		
		table.setRowHeight(50);
		
    	tabelPanel = new JPanel();
    	tabelPanel.setLocation(0,0);
    	tabelPanel.setBorder(BorderFactory.createLoweredBevelBorder());
    	
    	topPanel.add(txtScores);
    	tabelPanel.add(table);
    	tabelPanel.add(pegTable);
    	
    	btnPanel.add(btnStartGame);
    	btnPanel.add(btnRegister);
    	btnPanel.add(btnLogin); //add components to panels
    	btnPanel.add(btnSettings);
    	btnPanel.add(btnAbout);
    	btnPanel.add(btnQuit);
    	
    	colourPanel.add(btnRed);
    	colourPanel.add(btnYellow);
    	colourPanel.add(btnGreen);
    	colourPanel.add(btnBlue);
    	colourPanel.add(btnMagenta);
    	colourPanel.add(btnOrange);
    	colourPanel.add(btnSubmit);
    	
    	crr = new CustomCellRenderer();
    	table.setDefaultRenderer(Object.class, crr); //create new cell renderer for main table
    	
    	crrpegs = new CustomCellRendererPegs();
    	pegTable.setDefaultRenderer(Object.class, crrpegs); //create new cell renderer for peg table
    	
    	topPanel.add(tabelPanel);
    	topPanel.add(colourPanel);
    	topPanel.add(btnPanel);

    	this.setTitle("Mastermind Client: v0.1");
    	this.setResizable(false);
    	this.setSize(650,700);
    	this.setLocationRelativeTo(null);
    	this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    	
    }

}
